﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace SQLHelper
{
    /// <summary>
    /// 数据库操作的单例类：SQLHelperSingleton
    /// 这个类被拆成两个文件：SQLHelperSingleton.cs、SQLHelperAdapter.cs和SQLHelperEntity.cs
    /// 第一个主要写该类的一些基本属性及其配置方法，第二个主要写可供外部调用的SQL操作方法，最后一个主要写具体的SQL操作方法
    /// </summary>
    public partial class SQLHelperSingleton
    {
        public delegate void FinishWithDataSet (DataSet ds);
        public delegate void FinishWithDataReader (SqlDataReader reader);
        public delegate void FinishWithScalar (object obj);

        public delegate void ExecuteFail (string errorMsg);

        /// <summary>
        /// 查询数据库并获得一个dataSet对象
        /// </summary>
        /// <param name="sqlStr">查询语句</param>
        /// <param name="finish">包含一个DataSet类型参数的代理函数，可以使用这个参数完成任务</param>
        private void QueryByDataSet (string sqlStr, FinishWithDataSet finish)
        {
            this.OpenConnection();
            
            this.cmd.CommandText = sqlStr;
            SqlDataAdapter da = new SqlDataAdapter(this.cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            //将获取到的dataSet传递给外部（代理），外部可以利用这个dataSet完成任务
            if ( finish != null )
            {
                finish(ds);
            }

            da.Dispose();
            ds.Dispose();

            this.CloseConnection();
        }

        /// <summary>
        /// 查询数据库并获得一个dataReader对象
        /// </summary>
        /// <param name="sqlStr">查询语句</param>
        /// <param name="finish">包含一个dataReader类型参数的代理函数，可以使用这个参数完成任务</param>
        private void QueryByDataReader (string sqlStr, FinishWithDataReader finish)
        {
            this.OpenConnection();

            this.cmd.CommandText = sqlStr;
            SqlDataReader dr = this.cmd.ExecuteReader();

            if ( finish != null )
            {
                finish(dr);
            }

            dr.Dispose();

            this.CloseConnection();
        }

        private void QueryScalar (string sqlStr, FinishWithScalar finish)
        {
            this.OpenConnection();
            this.cmd.CommandText = sqlStr;

            object obj = this.cmd.ExecuteScalar();
            if ( finish != null )
            {
                finish(obj);
            }

            this.CloseConnection();
        }

        /// <summary>
        /// 数据库更删改操作
        /// </summary>
        /// <param name="sqlStr"></param>
        private void ExecuteNonQuery (string sqlStr)
        {
            this.OpenConnection();

            this.cmd.CommandText = sqlStr;
            this.cmd.ExecuteNonQuery();

            this.CloseConnection();
        }
    }
}
